package com.wuyou.mid;

import javax.swing.*;
import java.util.*;

/**
 * 1234. 替换子串得到平衡字符串
 */
public class BalancedString {

    public static void main(String[] args) {
//        String s = "WWEQERQWQWWRWWERQWEQ";  // 4
        String s = "WWWEQRQEWWQQQWQQQWEWEEWRRRRRWWQE"; // 5

        System.out.println(sol_1(s));
    }

    public static int sol_1(String s) {
        int[] letCountArr = new int[26];
        char[] chars = s.toCharArray();
        Set<Character> set = new HashSet<>();
        int letCountAvg = s.length() / 4;
        for (int i = 0; i < s.length(); i++) {
            int letCounttemp = ++letCountArr[chars[i] - 'A'];
            if (letCounttemp > letCountAvg) {
                set.add(chars[i]);
            }
        }
        if (check(letCountAvg, letCountArr)) {
            return 0;
        }
        int l = 0, r = 0, res = s.length();
        while (r < s.length()) {
            char c = chars[r];
            letCountArr[c - 'A']--;
            while (l < s.length() && check(letCountAvg, letCountArr)) {
                res = Math.min(res, r - l + 1);
                letCountArr[chars[l] - 'A']++;
                l++;
            }
            r++;
        }
        return res;
    }


    public static boolean check(int avg, int[] letCountArr) {
        if (letCountArr['Q' - 'A'] <= avg && letCountArr['W' - 'A'] <= avg && letCountArr['E' - 'A'] <= avg && letCountArr['R' - 'A'] <= avg) {
            return true;
        }
        return false;
    }


}
